import * as request from "superagent"

type VerifyUrl = 'https://buy.itunes.apple.com/verifyReceipt' | 'https://sandbox.itunes.apple.com/verifyReceipt'

interface Receipt {
  "purchase_date_ms": string,
  "unique_identifier": string,
  "transaction_id": string,
  "quantity": string,
  "unique_vendor_identifier": string,
  "item_id": string,
  "product_id": string
}

interface ReceiptResponse {
  receipt?: Receipt
  status: number
}

export default class IAPVerifier {

  url: VerifyUrl

  constructor(url: VerifyUrl) {
    this.url = url
  }

  async validate(receipt: any): Promise<ReceiptResponse> {

    const res = await request.post(this.url)
      .parse(request.parse['application/json'])
      .send(receipt)

    return res.body
  }
}
